import axios, { AxiosError } from 'axios'
import { Result } from '@/types/result'
import { Action, ElMessage, ElMessageBox } from 'element-plus'
import { userStore } from '@/store/userStore'
import router from '@/router/'

const request = axios.create({
  baseURL: import.meta.env.VITE_API_BASEURL
})

// 请求拦截器
request.interceptors.request.use(function (config) {
  const store = userStore()

  // 统一设置请求token
  const token = store.token

  if (token && config.headers) {
    config.headers.xiaohongToken = `${token}`
  }

  // 加上时间戳，防止浏览器缓存
  if (config.method === 'post') {
    config.data = {
      ...config.data
    }
    config.params = {
      _t: Date.now()
    }
  } else if (config.method === 'get') {
    config.params = {
      _t: Date.now(),
      ...config.params
    }
  }

  return config
}, function (error) {
  return Promise.reject(error)
})

// 控制登录过期的锁
let isRefreshing = false

// 响应拦截器
request.interceptors.response.use(function (config) {
  const store = userStore()

  // 统一处理接口响应错误，
  const data:Result = config.data as Result

  if (data && data.code === 20000) {
    // 请求成功
    return config
  } else if (data.code === 20001) {
    // 请求失败
    ElMessage({
      message: data.message,
      type: 'error',
      duration: 1000
    })
    return Promise.reject(data.message)
  } else if (data.code === 40001) {
    if (isRefreshing) return Promise.reject(data.message)
    isRefreshing = true
    // 登录过期或未登录
    ElMessageBox.alert('当前登录信息已失效，即将前往登录页面', '提示', {
      confirmButtonText: '确定',
      callback: (action: Action) => {
        store.logout()
        router.push({
          name: 'Login',
          query: {
            redirect: router.currentRoute.value.fullPath
          }
        })
      }
    })
    isRefreshing = false
    return Promise.reject(data.message)
  } else {
    // 服务器错误
    ElMessage({
      message: '服务器错误',
      type: 'error',
      duration: 2000
    })
    return Promise.reject(Object)
  }
}, function (error:AxiosError) {
  if (error.response?.status === 444) {
    ElMessage({
      message: error.response.data as string,
      type: 'error',
      duration: 2000
    })
  } else {
    ElMessage({
      message: error.message as string,
      type: 'error',
      duration: 2000
    })
    return Promise.reject(error)
  }
})

export default request
